//
//  SrnTeacherAppDelegate.m
//  SrnTeacher
//
//  Created by iDeneb on 11/21/09.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import <CoreFoundation/CoreFoundation.h>


#import "SrnTeacherAppDelegate.h"
#import "SwitchViewController.h"

#import "AsyncSocket.h"
#import "User.h"
#import "Stat.h"

#define WELCOME_MSG  0
#define ECHO_MSG     1
#define NOTNEW_MSG   2
#define NOTOPEN_MSG  3
#define NOTCLOSE_MSG  4
#define NOTALLOW_MSG  6
#define HIDE_MSG   6
#define RESULT_MSG   7
#define REQ_RESULT_MSG 8

#define FORMAT(format, ...) [NSString stringWithFormat:(format), ##__VA_ARGS__]

@implementation SrnTeacherAppDelegate

@synthesize window;
@synthesize viewController;
@synthesize listenSocket;
@synthesize ipaddress;
@synthesize listOfItems;
@synthesize tabBarController;
@synthesize currid;
@synthesize udb;
@synthesize isNew;
@synthesize isOpen;
@synthesize isHide;
@synthesize isShow;
@synthesize isClose;
@synthesize listOfAllUsers;

- (void) setPort:(int) listenport
{
	port = listenport;
}

- (void) setUserCount:(int) count{
	userCount = count;
}

- (void) setUserLimit:(int) limit{
	userLimit = limit;
}

-(IBAction)resultsClicked:(id)sender{
	NSLog(@"results Clicked");
}

-(int)port{
	return port;
}

-(int)userCount{
	return userCount;
}

-(int)userLimit{
	return userLimit;
}

- (id)init
{
	if(self = [super init])
	{
		listenSocket = [[AsyncSocket alloc] initWithDelegate:self];
		connectedSockets = [[NSMutableArray alloc] initWithCapacity:1];
		listOfItems = [[NSMutableArray alloc] init];
		listOfAllUsers = [[NSMutableArray alloc] init];
		
		isRunning = NO;
		port = 5224;
		userLimit = 10;
		userCount = 0;
		isNew = NO;
		isOpen = NO;
		isHide = NO;
		isShow = NO;
		isClose = NO;
	}
	return self;
}


- (void)applicationDidFinishLaunching:(UIApplication *)application {    
	NSLog(@"Ready");
	
	[listenSocket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
    
	
	
	// Override point for customization after application launch
	[window addSubview:viewController.view];
	[viewController initView];
    [window makeKeyAndVisible];
}

+(SrnTeacherAppDelegate *)App{
	return (SrnTeacherAppDelegate *)[[UIApplication sharedApplication]delegate];
}

- (void)dealloc {
    [window release];
	[viewController release];
    [super dealloc];
}

- (BOOL)startStop:(id)sender
{
	if(!isRunning)
	{
		
		if(port < 0 || port > 65535)
		{
			port = 0;
		}
		
		NSError *error = nil;
		if(![listenSocket acceptOnPort:port error:&error])
		{
			//[self logError:FORMAT(@"Error starting server: %@", error)];
			return NO;
		}
		
		
		
		NSString *socketInfo = [NSString stringWithFormat:@"ip %@, port %hu \n", [listenSocket localHost],[listenSocket localPort]];
		
		//[self logInfo:FORMAT(@"Echo server started on port %hu", [listenSocket localPort])];
		isRunning = YES;
		
	}
	else
	{
		[listenSocket disconnect];
		
		int i;
		for(i = 0; i < [connectedSockets count]; i++)
		{
			[[connectedSockets objectAtIndex:i] disconnect];
		}
		
		//[self logInfo:@"Stopped Echo server"];
		isRunning = false;
	}
	
	return YES;
}

- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket
{
	[connectedSockets addObject:newSocket];
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
	//[self logInfo:FORMAT(@"Accepted client %@:%hu", host, port)];
	userCount ++;
	[viewController.secondviewcontroller updateUser];
	
	NSString *welcomeMsg = @"Welcome SRN\r\n";
	NSData *welcomeData = [welcomeMsg dataUsingEncoding:NSUTF8StringEncoding];
	
	[sock writeData:welcomeData withTimeout:-1 tag:WELCOME_MSG];
	
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
	[sock readDataToData:[AsyncSocket CRLFData] withTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{   
	NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length] - 2)];
	NSString *msg = [[[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding] autorelease];
	
	if ([msg localizedCompare:@"request result"] == 0) {
		NSLog(@"request result");
		NSString *remsg;
		int reTag = 0;
		if (isClose == NO) {
			remsg = @"not close\r\n";
			reTag = NOTCLOSE_MSG;			
		}else if (isHide == YES) {
			remsg = @"not show\r\n";
			reTag = HIDE_MSG;
		} else{
			NSMutableString *ms = [[NSMutableString alloc] initWithCapacity:150];
			[ms appendString:@"stats "];
			NSMutableArray *stats = [udb getStatByNum:currid];
			int len = [stats count];
			for (int j=0; j<len; j++) {
				Stat *s = [stats objectAtIndex:j];
				NSString *cc = [NSString stringWithFormat:@"%d", s.count];
				[ms appendString:cc];
				[ms appendString:@","];
				[ms appendString:s.choice];
				[ms appendString:@";"];	
			}
			[ms appendString:@"\r\n"];
			remsg = [NSString stringWithString: ms];			
			reTag = RESULT_MSG;		
		}
		NSData *redata = [remsg dataUsingEncoding:NSUTF8StringEncoding];
		[sock writeData:redata withTimeout:-1 tag:reTag];
		return;
		
	}
	
	if(msg)
	{
		NSArray *listTokens = [msg componentsSeparatedByString:@";"];
		if([listTokens count] >1)
		{
			NSString * curUsername =  (NSString *)[listTokens objectAtIndex:0];
			int i=0;
			BOOL isMuted = NO;
			BOOL isVoted = NO;
			for(;i< [listOfItems count]; i++)
			{
				User *tempUser = [listOfItems objectAtIndex:i];
				if([tempUser.username localizedCompare:curUsername] == 0)
					//&& tempUser.muted)
				{
					isVoted = YES;
					break;
				}
			}
			
			for(int j=0;j < [listOfAllUsers count];j++)
			{
				User *tempUser = [listOfAllUsers objectAtIndex:j];
				if([tempUser.username localizedCompare:curUsername] == 0
					&& tempUser.muted)
				{
					isMuted = YES;
					break;
				}
			}
			
			if(isNew == NO || (isNew ==YES && isOpen == NO) || isMuted == YES || isVoted == YES)  {
				NSString *remsg;
				int ttag = 0;
				if (isNew == NO){
					remsg = @"not new\r\n";
					ttag = NOTNEW_MSG;
				} else if (isOpen == NO){
					remsg = @"not open\r\n";
					ttag = NOTOPEN_MSG;
				} else if (isMuted == YES){
					remsg = @"not allow\r\n";
					ttag = NOTALLOW_MSG;
				} else if (isVoted == YES) {
					remsg = @"have voted\r\n";
					ttag = 1;
				} else {
					remsg =@"unknow error\r\n";
					ttag = 1;
				}
				
				NSData *redata = [remsg dataUsingEncoding:NSUTF8StringEncoding];
				[sock writeData:redata withTimeout:-1 tag:ttag];
				return;
			}
			
			if(i >= [listOfItems count])
			  {
				 User *user = [User alloc];
				 user.username = (NSString *)[listTokens objectAtIndex:0];
				 user.choice = (NSString *)[listTokens objectAtIndex:1];
				 user.sock = sock;
				 user.removed = NO;
				 user.muted = NO;
				 [viewController.secondviewcontroller updateResult:user];
				 [viewController.manageviewcontroller updateResult];
             [sock writeData:data withTimeout:-1 tag:ECHO_MSG];}
			
		} else{
			 [sock writeData:data withTimeout:-1 tag:ECHO_MSG];			
		}
	}
	else
	{ 
	   [sock writeData:data withTimeout:-1 tag:ECHO_MSG];
	   NSLog(@"Error converting received data into UTF-8 String");
	}
	
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
	//[self logInfo:FORMAT(@"Client Disconnected: %@:%hu", [sock connectedHost], [sock connectedPort])];
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
	if(userCount > 0)
		userCount--;
	
	[viewController.secondviewcontroller updateUser];
	[connectedSockets removeObject:sock];
}


@end